import {offset} from './config'

export default {
  bind(el, binding) {
    const stop = binding.modifiers.stop || false
    const prevent = binding.modifiers.prevent || false
    const callback = binding.value

    let moveCount = 0

    let start = {
      x: null,
      y: null
    }
    let dir = {
      x: 'nomove',
      y: 'nomove'
    }
    let minDir = {
      x: 'nomove',
      y: 'nomove'
    }
    let moveList = []

    const end = function(event){
      if(event.changedTouches.length > 1 || moveList.length < offset)
        return

      if(start.x > moveList[moveList.length - 1].x)
        dir.x = 'left'
      else if(start.x < moveList[moveList.length - 1].x)
        dir.x = 'right'

      if(start.y > moveList[moveList.length - 1].y)
        dir.y = 'top'
      else if(start.y < moveList[moveList.length - 1].y)
        dir.y = 'bottom'

      if(moveList[0].x > moveList[moveList.length - 1].x)
        minDir.x = 'left'
      else if(moveList[0].x < moveList[moveList.length - 1].x)
        minDir.x = 'right'
      else minDir.x = dir.x

      if(moveList[0].y > moveList[moveList.length - 1].y)
        minDir.y = 'top'
      else if(moveList[0].y < moveList[moveList.length - 1].y)
        minDir.y = 'bottom'
      else minDir.y = dir.y

      callback({
        type: 'swipe',
        dir,
        el,
        minDir,
        start,
        end: moveList.length ? moveList[moveList.length - 1] : start,
        e: event
      })

      if(stop)
        event.stopPropagation && event.stopPropagation()
      if(prevent)
        event.preventDefault()

    }

    el.addEventListener('touchstart', function(event){

      if(event.changedTouches.length > 1){
        return
      }

      const touch = event.changedTouches[0]

      moveList = []

      moveCount = 0

      start = {
        x: null,
        y: null
      }

      dir = {
        x: 'nomove',
        y: 'nomove'
      }

      minDir = {
        x: 'nomove',
        y: 'nomove'
      }

      if(stop)
        event.stopPropagation()
      if(prevent)
        event.preventDefault()

    }, false)

    el.addEventListener('touchmove', function(event){

      if(event.changedTouches.length > 1){
        return
      }

      const touch = event.changedTouches[0]

      if(moveList.length < offset){
        moveCount ++
        return moveList.push({
          x: touch.pageX,
          y: touch.pageY
        })
      }
      else if(moveCount === offset){
        moveCount ++
        start.x = touch.pageX
        start.y = touch.pageY
      }

      moveList.shift()

      moveList.push({
        x: touch.pageX,
        y: touch.pageY
      })

      if(stop)
        event.stopPropagation()
      if(prevent)
        event.preventDefault()

    }, false)

    el.addEventListener('touchend', end, false)
    el.addEventListener('touchleave', end, false)
    el.addEventListener('touchcancel', end, false)
  }
}
